<?php

class UserStatisticsModel
{
    private $userStatisticsKeyPrefix    =   'US/';
    private $diaryListKeyPrefix         =   'DL/';
    private $followKeyPrefix            =   'FI/';
    private $commentKeyPrefix           =   'CI/';
    private $likeKeyPrefix              =   'LI/';
    private $topicKeyPrefix             =   'TP/';
    private $topicFavoriteKeyPrefix 	=   'CTP/';
    private $slaveKey                   =   '/slave';
    private $diaryListCacheModel;
    private $followModel;
    
    public function __construct(){
        $this->diaryListCacheModel    =    new DiaryListCacheModel();
        $this->followModel            =    new FollowModel();
    }

    public function initUserStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM001';
            return  FALSE;
        }

        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $result =   Storage::addData($key, NULL);
        if (empty($result))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }
        return  $result;
    }/*}}}*/

    public function userStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM001';
            return  FALSE;
        }
        $data   =   array();
        isset($info['diaryTimes'])      &&  $data['diaryTimes']         =   $info['diaryTimes'];
        isset($info['secretDiaryTimes'])&&  $data['secretDiaryTimes']   =   $info['secretDiaryTimes'];
        isset($info['commentTimes'])    &&  $data['commentTimes']       =   $info['commentTimes'];
        isset($info['commentMeTimes'])  &&  $data['commentMeTimes']     =   $info['commentMeTimes'];
        isset($info['followMeTimes'])   &&  $data['followMeTimes']      =   $info['followMeTimes'];
        isset($info['meFollowTimes'])   &&  $data['meFollowTimes']      =   $info['meFollowTimes'];
        isset($info['likeTimes'])       &&  $data['likeTimes']          =   $info['likeTimes'];
        isset($info['likeMeTimes'])     &&  $data['likeMeTimes']        =   $info['likeMeTimes'];
        isset($info['shareTimes'])      &&  $data['shareTimes']         =   $info['shareTimes'];
        isset($info['shareMeTimes'])    &&  $data['shareMeTimes']       =   $info['shareMeTimes'];
        isset($info['messageTimes'])    &&  $data['messageTimes']       =   $info['messageTimes'];
        isset($info['newCommentTimes']) &&  $data['newCommentTimes']    =   $info['newCommentTimes'];
        isset($info['newFollowTimes'])  &&  $data['newFollowTimes']     =   $info['newFollowTimes'];
        // 有关于我的任何操作都往newlikemetimes中加1
        isset($info['newLikeMeTimes'])  &&  $data['newLikeMeTimes']     =   $info['newLikeMeTimes'];
        isset($info['blackMeTimes'])    &&  $data['blackMeTimes']       =   $info['blackMeTimes'];
        isset($info['meBlackTimes'])    &&  $data['meBlackTimes']       =   $info['meBlackTimes'];
        // 圈子评论我的动态
        isset($info['newTopicComment']) &&  $data['newTopicComment']    =   $info['newTopicComment'];
        // IOS中评论我的轮询
        isset($info['newCommentMeTimes']) &&  $data['newCommentMeTimes']    =   $info['newCommentMeTimes'];
        // 圈子话题数
        isset($info['topicTimes'])      &&  $data['topicTimes']         =   $info['topicTimes'];
        isset($info['topicFavorTimes']) &&  $data['topicFavorTimes']    =   $info['topicFavorTimes'];

        if (empty($data))   return  TRUE;
        $this->diaryListCacheModel->addUserCount($info['uid'], $data);
        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $result =   Storage::limitUpdate($key, $data);

        return  TRUE;
    }/*}}}*/

    public function getStatisticsByUid($uid)
    {
        if (empty($uid)) return false;

        $result = $this->diaryListCacheModel->getUserCount($uid);
        if (empty($result)){
            $key = $this->userStatisticsKeyPrefix . $uid;
            $result = Storage::getData($key);
        }

        return  $result;
    }

    public function updateUserStatisticsByUid($uid, $data)
    {
        if (empty($uid) || empty($data)) return false;

        $key    =   $this->userStatisticsKeyPrefix. $uid;
        $result =   Storage::limitUpdate($key, $data);

        return  $result ? true : false;
    }

    /**
     * 获取用户计数
     * @param unknown $info
     * @return boolean|Ambigous
     */
    public function getUserStatistics ($info) {
        if (empty($info['uid'])) {
            AC::$errorNo = 'USM001';
            return FALSE;
        }
        
        // 获取usercount缓存
        $result = $this->diaryListCacheModel->getUserCount($info['uid']);
        // No.1 校验数值是否为大于等于0的有效值
        $is_effective_value = $this->checkParam($result, array(), TRUE);
        if ( empty($result) || !$is_effective_value || (intval($result['addtime'])  < (AC::SERVER_TIME - 86400 )) || !isset($result['coin'])) {
            // 取数据库
            $statistics = $this->getUserStatisticsByUid($info['uid']);
            // 对比缓存与数据库是否一致，不一致所有计数重置
            $check = $this->checkParam($result, $statistics);
            if(!isset($result['coin'])){
                $check = false;
            }
            if (count($statistics) < 10 || !$check || empty($result)){
                // 重置计数
                $this->countUserInfo(array('uid' => $info['uid']));
            }
            
            $result = $this->diaryListCacheModel->getUserCount($info['uid']);
        }
        
        $result['uid'] = $info['uid'];
        return $result;
    }
    
    /**
     * 字段数值比较
     * @param unknown $a
     * @param unknown $b
     * @param string $only_check_number_is_positive
     * @return boolean
     */
    private function checkParam($a ,$b, $only_check_number_is_positive = FALSE){
        $result = TRUE;
        $param  = array('diaryTimes','secretDiaryTimes','commentTimes','commentMeTimes','likeTimes','likeMeTimes',
                'topicTimes','topicFavorTimes','meFollowTimes','followMeTimes','meBlackTimes');
        
        foreach ($param as $value){
            if ($a[$value] < 0) {
                $result = FALSE;
                break;
            }
            
            if ($only_check_number_is_positive ) continue;
            
            if ($a[$value] != $b[$value]){
                $result = FALSE;
                break;
            }
        }
        return $result;
    }
    
    private function statisticalErrorCount($field){
        // 获取计数错误信息
        $this->diaryListCacheModel->getStatisticalErrorCount($field);
        // 计数加1
        $this->diaryListCacheModel->addStatisticalErrorCount($field, 1);
    }
    
    /**
     * 获取statistics数据
     * @param unknown $uid
     * @return Ambigous <unknown, boolean, mixed, multitype:, Ambigous>
     */
    public function getUserStatisticsByUid($uid){
        $key = $this->userStatisticsKeyPrefix . $uid . $this->slaveKey;
        $result = Storage::getData($key);
        if (empty($result)){
            // 初始化数据库
            $this->initUserStatistics(array('uid' => $uid));
        }
        return $result;
    }
    
    public function getUserStatisticsDetail($uid)
    {
        if (empty($uid)) return array();

        $key = $this->userStatisticsKeyPrefix . $uid . $this->slaveKey;
        $result = Storage::getData($key);

        return $result;
    }

    /**
     * 重建粉丝,好友列表
     * @param unknown $info
     */
    public function rebuildUserFollow($info){

        RedisPool::addGearmanJob('reset_followers', array("uid"=>$info['uid']), $info['uid']);
        return '';
    }
    
    // 获取用户话题总数
    public function rebuildTopicTimes($uid){
        if (empty($uid))
        {
            AC::$errorNo = 'TPM001';
            return FALSE;
        }
        
        $where  =   array('uid' => $uid,'status'=>0);

        $key    =   $this->topicKeyPrefix. 0;
        $result =   Storage::countDataRow($key, $where);
        return  $result;
    }
    // 获取用户话题总数
    public function rebuildTopicFavorTimes($uid){
    	if (empty($uid))
    	{
            AC::$errorNo = 'TPM001';
            return FALSE;
    	}
    
    	$where  =   " uid = ".$uid." AND status = 0 AND position <= 1 ";
    
    	$key    =   $this->topicFavoriteKeyPrefix. $uid;
    	$result =   Storage::countDataRow($key, $where);
    	return  $result;
    }
    
    /**
     * 重建黑名单列表
     * @param unknown $info
     */
    public function rebulidUserBlacked($info){
        // 重建黑名单
        $this->diaryListCacheModel->removeBlacked($info['uid']);
        $key    =   $this->followKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   array('type' => 2,'status'=>2);
        $blacked_result =   Storage::getConditionManyData($key, $where);
        
        foreach($blacked_result as $black ){
            $this->diaryListCacheModel->addBlackList($black['uid'], $black['fUid'], $black['time']);
        }
    }
    
    /**
     * 计算用户信息,初始化
     * @param unknown $info
     */
    public function countUserInfo($info){
        $data = array();
        // 公开日记
        $data['diaryTimes']       =   $this->countDiaryTotal($info);
        
        // 私密日记
        $info['secret'] =   1;
        $data['secretDiaryTimes'] =   $this->countDiaryTotal($info);
        
        // 喜欢数
        $info['type']   =   2;
        $data['likeTimes']       =   $this->countLikesTotal($info);
        
        // 喜欢我的
        $info['type']   =   1;
        $data['likeMeTimes']     =   $this->countLikesTotal($info);
        
        // 评论我的
        $info['type']   =   1;
        $data['commentMeTimes']  =   $this->countCommentsTotal($info);
        
        // 我评论的
        $info['type']   =   2;
        $data['commentTimes']    =   $this->countCommentsTotal($info);
        
        // 粉丝数
        $info['type']   =   1;
        $info['status'] =   0;
        $data['followMeTimes']   =   $this->followModel->countTotal($info);
        
        // 关注数
        $info['type']   =   2;
        $info['status'] =   0;
        $data['meFollowTimes']   =   $this->followModel->countTotal($info);
        
        // 拉黑数
        $info['type']   =   2;
        $info['status'] =   2;
        $data['meBlackTimes']    =   $this->followModel->countTotal($info);
        
        // 拉黑我的
        $info['type']   =   1;
        $info['status'] =   2;
        $data['blackMeTimes']    =   $this->followModel->countTotal($info);
        
        // 话题数
        $data['topicTimes']      =   $this->rebuildTopicTimes($info['uid']);
        
        // 话题数
        $data['topicFavorTimes']      =   $this->rebuildTopicFavorTimes($info['uid']);
        
        // 数据库校正
        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $result =   Storage::setData($key, $data);
       
        //返回金币数
        $api = UK::getMallApi($info['uid']);
        $coin = $api->getUserCoin();
        $data['coin'] = intval($coin['balance']);
        
        // redis初始化
        $data['addtime'] = AC::SERVER_TIME;
        $this->diaryListCacheModel->initUserCount($info['uid'], $data);
        $data['uid']    =    $info['uid'];
        
        return $data;
    }
    
    // 喜欢
    public function countLikesTotal($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'DLM009';
            return  FALSE;
        }
        $key    =   $this->likeKeyPrefix. $info['uid'].$this->slaveKey;
    
        $where  =   array('likeType' => $info['type']);

        $result =   Storage::countDataRow($key, $where);
        return  $result;
    }/*}}}*/
    
    // 喜欢,评论
    public function countCommentsTotal($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'DLM009';
            return  FALSE;
        }
        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
    
        $where  =   array('commentType' => $info['type']);
    
        $result =   Storage::countDataRow($key, $where);
        return  $result;
    }/*}}}*/
    
    // 日记统计
    public function countDiaryTotal($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'DLM009';
            return  FALSE;
        }
        $key    =   $this->diaryListKeyPrefix. $info['uid'].$this->slaveKey;
        
        $where  =   array('secret' => 0, 'status' => 0);
        if (!empty($info['secret']))   $where  =   array('secret' => 1, 'status' => 0);
        
        $result =   Storage::countDataRow($key, $where);
        return  $result;
    }/*}}}*/
    
    // 关注
    public function countFollowTotal($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'FWM002';
            return  FALSE;
        }
        $where  =   array('type' => 1,'status' => $info['status']);
        if ($info['type'] == 1 && $info['status'] == '2'){
            $where  =   array('type' => 1,'status'=>$info['status']);
        }
        if (isset($info['type']) && (2 ==  $info['type']))
        {
            $where  =   array('type' => 2,'status' => $info['status']);
        }
        $key    =   $this->followKeyPrefix. $info['uid'].$this->slaveKey;
    
        $result =   Storage::countDataRow($key, $where);
        return  $result;
    }/*}}}*/
    
    public function setUserStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM001';
            return  FALSE;
        }
        // 初始化
        $this->diaryListCacheModel->initUserCount($info['uid'], $info);
        $data   =   array();
        isset($info['diaryTimes'])      &&  $data['diaryTimes']         =   $info['diaryTimes'];
        isset($info['secretDiaryTimes'])&&  $data['secretDiaryTimes']   =   $info['secretDiaryTimes'];
        isset($info['followMeTimes'])   &&  $data['followMeTimes']      =   $info['followMeTimes'];
        isset($info['meFollowTimes'])   &&  $data['meFollowTimes']      =   $info['meFollowTimes'];
        isset($info['blackMeTimes'])    &&  $data['blackMeTimes']       =   $info['blackMeTimes'];
        isset($info['meBlackTimes'])    &&  $data['meBlackTimes']       =   $info['meBlackTimes'];
        if (empty($data))   return  TRUE;

        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $result =   Storage::setData($key, $data);

        return  $result;
    }/*}}}*/

    public function resetMessageStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM001';
            return  FALSE;
        }

        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('messageTimes' => 0);
        $result =   Storage::setData($key, $data);

        return  $result;
    }/*}}}*/

    
    public function resetNewFansStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }

        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('newFollowTimes' => 0);
        $result =   Storage::setData($key, $data);

        return  $result;
    }/*}}}*/


    public function resetNewCommentTimesStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }

        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('newCommentTimes' => 0);
        $result =   Storage::setData($key, $data);

        return  $result;
    }/*}}}*/
    // 重置圈子中评论我的寻轮
    public function resetNewTopicCommentTimesStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }
    
        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('newTopicComment' => 0);
        $result =   Storage::setData($key, $data);
    
        return  $result;
    }/*}}}*/
    // 重置IOS中评论我的轮询
    public function resetNewCommentMeTimesStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }
    
        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('newCommentMeTimes' => 0);
        $result =   Storage::setData($key, $data);
    
        return  $result;
    }/*}}}*/
    // 重置关于我的轮询
    public function resetNewLikeMeTimesStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }
    
        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('newLikeMeTimes' => 0);
        $result =   Storage::setData($key, $data);
    
        return  $result;
    }/*}}}*/
      
    // 重置情感天地的轮询
    public function resetNewChatMessageTimesStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }
    
        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('newChatMessage' => 0);
        $result =   Storage::setData($key, $data);
    
        return  $result;
    }/*}}}*/
    
    // 重置圈子最新话题的轮询
    public function resetNewTopicMessageTimesStatistics($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'USM002';
            return  FALSE;
        }
    
        $key    =   $this->userStatisticsKeyPrefix. $info['uid'];
        $data   =   array('newTopicMessage' => 0);
        $result =   Storage::setData($key, $data);
    
        return  $result;
    }/*}}}*/

    public function resetAysCommentTimesStatistics($uid)
    {
        $key    =   $this->userStatisticsKeyPrefix. $uid;
        $data   =   array('aysCommentTimes' => 0);
        $result =   Storage::setData($key, $data);

        return  $result;
    }
}

